package com.ai.wx.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ai.core.cache.AICacheManager;
import com.ai.core.constant.GlobalConstant;
import com.ai.core.dao.BaseDaoI;
import com.ai.wx.entity.AgentPromotion;
import com.ai.wx.entity.Product;
import com.ai.wx.entity.ProductPromotion;
import com.ai.wx.exception.FlowMarketException;
import com.ai.wx.pojo.ProductPrice;
import com.ai.wx.service.AgentPromotionService;
import com.ai.wx.service.ProductService;

@Service
public class ProductServiceImpl implements ProductService{
	private AICacheManager aiCacheManager = AICacheManager.getInstance();

	private Map<Integer,List<Product>> m_product = null;
	private Map<String,List<ProductPromotion>> m_product_promotion = null;
	public ProductServiceImpl() {
		if (m_product == null) {
			m_product = aiCacheManager.getMap(GlobalConstant.CACHE_PRODUCT_MAP);
		}
		if (m_product_promotion == null) {
			m_product_promotion = aiCacheManager.getMap(GlobalConstant.CACHE_PRODUCT_PROMOTION_MAP);
		}
	}
	@Autowired
	private BaseDaoI<Product> productDao;
	@Autowired
	private BaseDaoI<ProductPromotion> productPromotionDao;
	@Autowired
	private BaseDaoI<AgentPromotion> agentPromoitonDao;
	@Autowired
	private AgentPromotionService agentPromotionService;

	public void loadCache() {
		m_product.clear();
		List<Product> cmccProducts= getProductsByOperId(GlobalConstant.OPER_ID_CMCC);
		List<Product> cuccProducts= getProductsByOperId(GlobalConstant.OPER_ID_CUCC);
		List<Product> ctccProducts= getProductsByOperId(GlobalConstant.OPER_ID_CTCC);
		m_product.put(GlobalConstant.OPER_ID_CMCC, cmccProducts);
		m_product.put(GlobalConstant.OPER_ID_CUCC, cuccProducts);
		m_product.put(GlobalConstant.OPER_ID_CTCC, ctccProducts);
		
		List<Product> allProducts=new ArrayList<Product>();
		allProducts.addAll(cmccProducts);
		allProducts.addAll(cuccProducts);
		allProducts.addAll(ctccProducts);

		m_product.put(GlobalConstant.OPER_ID_ALL, allProducts);
		
		m_product_promotion.clear();
	}
	
	public List<Product> getProductsByOperId(Integer operId){ 
		if(m_product.containsKey(operId)){
			return m_product.get(operId);
		}
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("operatorId", operId);
		String hql = " from Product t where t.operatorId =:operatorId order by t.seq asc";
		List<Product> list = productDao.find(hql,params); 
		return list;
	}
	
	public ProductPromotion getProdPromById(String productId, int promotionRate) {
		List<ProductPromotion> productPromotionList;

		productPromotionList = m_product_promotion.get(productId);
		if (m_product_promotion.get(productId) == null) {
			String hql = "from ProductPromotion where state = 1 and productId =:productId";
			HashMap params = new HashMap();
			params.put("productId", productId);
			productPromotionList = productPromotionDao.find(hql, params);
		}
		
		ProductPromotion productPromotion = null;
		for (ProductPromotion obj : productPromotionList) {
	        if(obj.getPromotionRate() == promotionRate){
	        	productPromotion = obj;
	        	break;
	        }
        }
		return productPromotion;
	}

	public Product getProductById(String productId){  
		Product product = productDao.get(Product.class, productId);
		return product;
	}
 
	
	@Override
    public ProductPrice getProdPrice(String productId, String promotionCode) throws FlowMarketException {
		ProductPrice productPrice = new ProductPrice();
		Product product = null;
		List<Product> productList = m_product.get(GlobalConstant.OPER_ID_ALL);
		if(productList==null || productList.size()==0){
			product = getProductById(productId);
		}else{
			for (Product prod : productList) {
	            if(StringUtils.equals(prod.getProductId(), productId)){
	            	product = prod;
	            	break;
	            }
            }
		}
		if(product == null){
			throw new FlowMarketException("产品编号错误，系统中不存在对应的产品(产品编号："+productId+")");
		}
		productPrice.setTariff(product.getTariff()); 
		productPrice.setTotal(product.getTariff());
		if(StringUtils.isNotEmpty(promotionCode)){
			AgentPromotion agentPromotion=agentPromotionService.getAgentPromotionByCode(promotionCode); 
			productPrice.setAgentId(agentPromotion.getAgentId());
			productPrice.setPromRate(agentPromotion.getPromotionRate());
			if(agentPromotion != null){ 
				ProductPromotion prodProm = getProdPromById(productId, agentPromotion.getPromotionRate());
				if(prodProm!=null){ 
					int promotionTafiff =  product.getTariff()- prodProm.getDiscount(); 
					productPrice.setDiscount(prodProm.getDiscount());
					productPrice.setTotal(promotionTafiff);
					productPrice.setBrokerage(prodProm.getBrokerage());
				}
			} 
		} 
		return productPrice;
    }
	
	@Override
    public boolean chkPromCode(String promotionCode) {
		boolean isValid = false;
		if(StringUtils.isNotEmpty(promotionCode)){
			AgentPromotion agentPromotion=agentPromotionService.getAgentPromotionByCode(promotionCode); 
			if(agentPromotion != null){ 
				isValid = true;
			} 
		} 
		return isValid;
    }
}
